﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using Ti = System.Timers;
using System.IO;
using System.Net.Sockets;
using System.Net;
using System.Reflection.Emit;
using System.Threading;
using System.Runtime.InteropServices;
using NAudio.CoreAudioApi;

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        TcpListener listener;
        // user32dll控制系统音量，结果无法在service里使用
        /* user32法
        private Process p;
        private const int APPCOMMAND_VOLUME_MUTE = 0x80000;
        private const int APPCOMMAND_VOLUME_UP = 0x0a0000;
        private const int APPCOMMAND_VOLUME_DOWN = 0x090000;
        private const int WM_APPCOMMAND = 0x319;
        */

        public Service1()
        {
            InitializeComponent();
        }
        protected override void OnStart(string[] args)
        {
            if (!Directory.Exists(@"c:\shutdownlog\"))
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(@"c:\shutdownlog\");
                directoryInfo.Create();
            }
            OpenTCP();
        }

        protected override void OnStop()
        {
            listener.Stop();
        }

        private void Shutdown()
        {
            //关机
            int time = 1;    //单位为：秒
            File.AppendAllText(@"C:\shutdownlog\" + DateTime.Now.ToString("yyyyMM") + ".txt",
                           DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss shutdown ") +  Environment.NewLine);
            Process.Start("c:/windows/system32/shutdown.exe", "-s -t " + time);
        }
        private void OpenTCP()
        {
            listener = new TcpListener(IPAddress.Any, 5000);
            listener.Start();
            Thread th = new Thread(new ThreadStart(ReceiveMsg));
            th.Start();
            th.IsBackground = true;

        }
        public void ReceiveMsg()
        {

            while (true)
            {
                TcpClient client = listener.AcceptTcpClient();
                byte[] buffer = new byte[16];
                NetworkStream stream = client.GetStream();
                int len = stream.Read(buffer, 0, buffer.Length);
                string msg = Encoding.UTF8.GetString(buffer, 0, len);// Encoding.Unicode.GetString(buffer, 0, len);
                switch (msg)
                {
                    case "shutdown":                    
                        Shutdown();
                        break;
                    case "sysvol+":
                        SystemVolAdd();
                        break;
                    case "sysvol-":
                        SystemVolReduce();
                        break;
                    case "sysvol0":
                        SystemVolMute();
                        break;
                }

                stream.Flush();
                stream.Close();
                client.Close();

            }
        }
        /* user32法
        [DllImport("user32.dll")]
        public static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

        private void SystemVolAdd()
        {
            p = Process.GetCurrentProcess();
            for (int i = 0; i < 5; i++)
            {
                SendMessageW(p.Handle, WM_APPCOMMAND, p.Handle, (IntPtr)APPCOMMAND_VOLUME_UP);
            }
        }
        private void SystemVolReduce()
        {
            p = Process.GetCurrentProcess();
            for (int i = 0; i < 5; i++)
            {
                SendMessageW(p.Handle, WM_APPCOMMAND, p.Handle, (IntPtr)APPCOMMAND_VOLUME_DOWN);
            }
        }
        private void SystemVolMute()
        {
            p = Process.GetCurrentProcess();
            SendMessageW(p.Handle, WM_APPCOMMAND, p.Handle, (IntPtr)APPCOMMAND_VOLUME_MUTE);
        }
        */


        // NAudio法
        private MMDevice device;
        private MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();

        private void SystemVolAdd()
        {
            device = DevEnum.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
            float volume = device.AudioEndpointVolume.MasterVolumeLevelScalar;
            if (volume <= 0.8f)
            {
                device.AudioEndpointVolume.MasterVolumeLevelScalar += 0.2f;
            }
            else
            {
                device.AudioEndpointVolume.MasterVolumeLevelScalar = 1f;
            }
        }

        private void SystemVolReduce()
        {
            device = DevEnum.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
            float volume = device.AudioEndpointVolume.MasterVolumeLevelScalar;
            if (volume >= 0.2f)
            {
                device.AudioEndpointVolume.MasterVolumeLevelScalar -= 0.2f;
            }
            else
            {
                device.AudioEndpointVolume.MasterVolumeLevelScalar = 0;
            }
        }
        private void SystemVolMute()
        {
            device = DevEnum.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
            //静音/取消静音
            device.AudioEndpointVolume.Mute = !device.AudioEndpointVolume.Mute;
        }



    }
}
